package jhavelogger.data;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * A helper class to create database connections. If additional database
 * systems need to be supported in the future, consider making this class an
 * interface and creating multiple implementations of it (one per database
 * system that needs to be supported).
 * 
 * The required information (server, username, password) are loaded from
 * the database.properties file (stored at the top-level of the project).
 * For security's sake, this file is not included in SVN.
 * 
 * Relevant properties:
 * server: a full jdbc connection string. Example: jdbc:mysql://myserver.uwosh.edu:4381/mydatabase
 * username: username to connect with
 * password: password to connect with
 */
public class ConnectionFactory {
    /**
     * Creates a new database connection. The caller of this method is
     * responsible for eventually closing the connection
     * 
     * @return Connection object
     * @throws ClassNotFoundException if the particular database driver could not be loaded
     * @throws SQLException if a SQL error occured while connecting
     * @throws IOException if the database.properties could not be loaded
     */
    public Connection createConnection() throws ClassNotFoundException, SQLException, IOException {
	Properties dbProperties = new Properties();
	FileInputStream input = new FileInputStream("database.properties");
	dbProperties.load(input);
	    
	String url = dbProperties.getProperty("server");
	String userName = dbProperties.getProperty("user");
	String password = dbProperties.getProperty("password");
	
	Class.forName("com.mysql.jdbc.Driver");
	Connection connection = DriverManager.getConnection(url, userName, password);
	connection.setAutoCommit(false);
	return connection;
    }
}
